package cn.itcast.n4.deadLock.v1;
/**
 * ReentrantLock-锁超时解决哲学家就餐
 * @author yd
 * @date 2022/3/20 23:38
 * @version 1.0
 */

import cn.itcast.utils.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "w.TestDeadLock1")
public class TestDeadLock1 {
    public static void main(String[] args) {
        Chopstick1 c1 = new Chopstick1("1");
        Chopstick1 c2 = new Chopstick1("2");
        Chopstick1 c3 = new Chopstick1("3");
        Chopstick1 c4 = new Chopstick1("4");
        Chopstick1 c5 = new Chopstick1("5");
        new Philosopher1("苏格拉底", c1, c2).start();
        new Philosopher1("柏拉图", c2, c3).start();
        new Philosopher1("亚里士多德", c3, c4).start();
        new Philosopher1("赫拉克利特", c4, c5).start();
//        new Philosopher1("阿基米德", c1, c5).start();
        new Philosopher1("阿基米德", c5, c1).start();

    }



}

class Chopstick1 extends ReentrantLock {
    String name;

    public Chopstick1(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Chopstick{" +
                "name='" + name + '\'' +
                '}';
    }
}

@Slf4j(topic = "w.Philosopher")
class Philosopher1 extends Thread {
    Chopstick1 left;
    Chopstick1 right;

    public Philosopher1(String name, Chopstick1 left, Chopstick1 right){
        super(name);
        this.left = left;
        this.right = right;
    }


    public void eat(){
        log.debug("eating");
        Sleeper.sleep(1);
    }

    @Override
    public void run() {
        while (true){
            //尝试获取左手筷子
           if(left.tryLock()){
               //尝试获得右手筷子
               try {
                  if (right.tryLock()){
                      try{
                          eat();
                      }finally {
                          right.tryLock();
                      }
                  }
               } finally {
                   left.unlock();//释放自己手里的筷子
               }

           }

        }
    }

}
